﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfMail;
using Hisuntech.SystemFramework.Net.Mail;
using WcfMail.Interface;


namespace XMailUtil
{
    /// <summary>
    /// 虚拟邮件系统，将采用文件系统模拟邮件系统
    /// </summary>
    public class XMails : Emails
    {
        /// <summary>
        /// 邮件存放的本地路径
        /// </summary>
        public string MailPath=@"..\XMail";

        private void init()
        {
            if (!System.IO.Directory.Exists(MailPath))
                System.IO.Directory.CreateDirectory(MailPath);
        }

        public override bool Send(ISysMsg message)
        {
            MailPath = @"..\XMail\Send";
            init();
            string fileName =MailPath+"\\"+ message.MsgSubject  +".txt";
          
            System.IO.File.WriteAllText(fileName, message.MsgContent);
            return true;
        }

        public override bool Receive(ISysMsg message, bool delMail, int delMsgID)
        {
            MailPath = @"..\XMail\Receive";
            init();
            if (!System.IO.Directory.Exists(MailPath))
                return false;

            bool needMatching = !string.IsNullOrEmpty(this.MatchingTitle);

            foreach (string file in System.IO.Directory.GetFiles(MailPath))
            {
                MailMessageInfo msg = new MailMessageInfo();
                msg.MsgSubject = System.IO.Path.GetFileNameWithoutExtension(file);
                msg.MsgContent = System.IO.File.ReadAllText(file);
                //是否需要匹配邮件标题
                if (!needMatching ||
                    (needMatching && msg.MsgSubject.StartsWith(this.MatchingTitle))
                    )
                {
                    this.MessageQueue.Add(msg);
                    if (this.ReceiveAndDelete)
                        System.IO.File.Delete(file);
                }
               
            }
            return true;
        }

        public override bool DeleteInboxMail(bool isAll)
        {
            if (!System.IO.Directory.Exists(MailPath))
                return false;
            foreach (string file in System.IO.Directory.GetFiles(MailPath))
            {
                System.IO.File.Delete(file);
            }
            return  true;
        }
    }
}
